package com.xoa.dev.pz.service;

import com.xoa.dao.common.SysCodeMapper;

import com.xoa.dev.keyYouth.dao.PAdolescentMapper;
import com.xoa.dev.keyYouth.dao.PAidsMapper;
import com.xoa.dev.keyYouth.service.PAidsService;
import com.xoa.model.common.SysCode;
import com.xoa.model.enclosure.Attachment;

import com.xoa.model.users.Users;
import com.xoa.dev.pz.dao.*;
import com.xoa.dev.pz.model.PzPerson;
import com.xoa.dev.pz.model.PzPersonFlow;
import com.xoa.dev.pz.model.PzPersonWithBLOBs;
import com.xoa.service.users.UsersService;
import com.xoa.dao.party.GridInfoMapper;
import com.xoa.model.party.GridInfo;
import com.xoa.util.DateFormat;
import com.xoa.util.ExcelUtil;
import com.xoa.util.GetAttachmentListUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.L;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.netdisk.CheckAll;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by gsb on 2017/11/29.
 */
@Service
public class PzPersonService {

    @Resource
    private PzPersonMapper pzPersonMapper;

    @Resource
    private SysCodeMapper sysCodeMapper;

    @Resource
    private PzPersonFlowMapper pzPersonFlowMapper;

    @Resource
    private UsersService usersService;
    @Resource
    private GridInfoMapper gridInfoMapper;
    @Resource
    private MenuJdtMapper menuJdtMapper;

    @Resource
    private PzCorrectionMapper pzCorrectionMapper;

    @Resource
    private PzDrugMapper pzDrugMapper;

    @Resource
    private PzEasyAccidentMapper pzEasyAccidentMapper;

    @Resource
    private PzFullReleaseMapper pzFullReleaseMapper;

    @Resource
    private PzKeyPetitionMapper pzKeyPetitionMapper;

    @Resource
    private PzKeyYouthMapper pzKeyYouthMapper;

    @Resource
    private PzPersonServiceMapper pzPersonServiceMapper;

    @Autowired
    private PAidsMapper pAidsMapper;

    @Resource
    private PAdolescentMapper pAdolescentMapper;

    public ToJson<PzPersonWithBLOBs> insertSelective(PzPersonWithBLOBs pzPersonWithBLOBs, HttpServletRequest request){
        ToJson<PzPersonWithBLOBs> json = new ToJson<PzPersonWithBLOBs>();
        try {
            Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
            pzPersonWithBLOBs.setCreateUser(user.getUserId());
            pzPersonWithBLOBs.setCreateTime(DateFormat.getDatestr(new Date()));
            pzPersonWithBLOBs.setFlag2("0");
            if(!StringUtils.checkNull(pzPersonWithBLOBs.getAttachmentId())&&!StringUtils.checkNull(pzPersonWithBLOBs.getAttachmentName())){
                   pzPersonWithBLOBs.setPicture(1);
            }
            pzPersonWithBLOBs.setPicture(0);
            pzPersonMapper.insertSelective(pzPersonWithBLOBs);
            if(pzPersonWithBLOBs.getFlag1().equals("2")){
                PzPersonFlow flow=new PzPersonFlow();
                if(pzPersonWithBLOBs.getpId()!=null){
                    flow.setPersonId(String.valueOf(pzPersonWithBLOBs.getpId()));
                }
                pzPersonFlowMapper.insertSelective(flow);
            }
            json.setObject(pzPersonWithBLOBs);
            json.setFlag(0);
            json.setMsg("ok");
        }catch (Exception e){
            e.printStackTrace();
            json.setMsg("err");
            json.setFlag(1);
        }
        return json;

    }
    public ToJson<PzPersonWithBLOBs> deleteByPrimaryKey(Integer pId){
        ToJson<PzPersonWithBLOBs> json = new ToJson<PzPersonWithBLOBs>();
        try {
            int count=pzPersonMapper.upFlag2ByPId(pId);
            //删除该人员对应的业务信息和服务信息
            count+=pzCorrectionMapper.delByPersonId(pId);
            count+=pzDrugMapper.delByPersonId(pId);
            count+=pzEasyAccidentMapper.delByPersonId(pId);
            count+=pzFullReleaseMapper.delByPersonId(pId);
            count+=pzKeyPetitionMapper.delByPersonId(pId);
            count+=pzKeyYouthMapper.delByPersonId(pId);
            count+=pzPersonFlowMapper.delByPersonId(pId);
            count+=pzPersonServiceMapper.delByPersonId(pId);
            count+=pAidsMapper.delByPersonId(String.valueOf(pId));
            //count+=pAdolescentMapper.delByPersonId(String.valueOf(pId));
            if(count>0){
                json.setFlag(0);
                json.setMsg("ok");
            }
        }catch (Exception e){
            e.printStackTrace();
            json.setMsg("err");
            json.setFlag(1);
        }
        return json;

    }
    public ToJson<PzPersonWithBLOBs> updateByPrimaryKeySelective(PzPersonWithBLOBs record){
        ToJson<PzPersonWithBLOBs> json = new ToJson<PzPersonWithBLOBs>();
        try {
            if(record.getFlag1().equals("2")){
                if(pzPersonFlowMapper.queryById(record.getpId())==null){
                    PzPersonFlow flow=new PzPersonFlow();
                    if(record.getpId()!=null){
                        flow.setPersonId(String.valueOf(record.getpId()));
                    }
                    pzPersonFlowMapper.insertSelective(flow);
                }
            }else{
                pzPersonFlowMapper.deleteByPrimaryKey(record.getpId());
            }
            if(record.getpVehicles().equals("0")){
                record.setStr1("");
                record.setCarColor("");
                record.setCarNums(null);
                record.setCarType("");
            }
            if(record.getIsIndividual()==0){
                record.setShopName("");
                record.setStoreAddress("");
                record.setBusinessLicenseNumber(null);
                record.setCoveredArea("");
                record.setScopeOfOperation("");
                record.setMeasure(null);
                record.setFireHazard(null);
                record.setShopRemark("");
            }
            pzPersonMapper.updateByPrimaryKeySelective(record);
            json.setFlag(0);
            json.setMsg("ok");
        }catch (Exception e){
            e.printStackTrace();
            json.setMsg("err");
            json.setFlag(1);
        }
        return json;

    }

    public ToJson<PzPersonWithBLOBs> queryById(Integer pId, HttpServletRequest request){
        ToJson<PzPersonWithBLOBs> json = new ToJson<PzPersonWithBLOBs>();
        try {
            PzPersonWithBLOBs pzPersonWithBLOBs = pzPersonMapper.queryById(pId);
            //附件处理
            List<Attachment> attachmentList=new ArrayList<Attachment>();
            if(pzPersonWithBLOBs.getAttachmentName()!=null&&!"".equals(pzPersonWithBLOBs.getAttachmentName())){
                attachmentList= GetAttachmentListUtil.returnAttachment(pzPersonWithBLOBs.getAttachmentName(),pzPersonWithBLOBs.getAttachmentId(),"xoa" + (String) request.getSession().getAttribute("loginDateSouse"), GetAttachmentListUtil.MODULE_PZ_PERSON);
            }
            pzPersonWithBLOBs.setAttachmentList(attachmentList);
            SysCode sysCode = sysCodeMapper.getSingleCode("POLITICAL", pzPersonWithBLOBs.getpPolitical());
            if(sysCode!=null){
                pzPersonWithBLOBs.setpPoliticalStr(sysCode.getCodeName());
            }
            SysCode sysCode1 = sysCodeMapper.getSingleCode("DEGREE", pzPersonWithBLOBs.getpEducation());
            if(sysCode1!=null){
                pzPersonWithBLOBs.setpEducationStr(sysCode1.getCodeName());
            }
            SysCode sysCode2 = sysCodeMapper.getSingleCode("relationship", pzPersonWithBLOBs.getRelationship());
            if(sysCode2!=null){
                pzPersonWithBLOBs.setRelationshipName(sysCode2.getCodeName());
            }
            SysCode sysCode3 = sysCodeMapper.getSingleCode("registeredResidenceType", pzPersonWithBLOBs.getAccountCategory());
            if(sysCode3!=null){
                pzPersonWithBLOBs.setAccountCategoryName(sysCode3.getCodeName());
            }
            SysCode sysCode4 = sysCodeMapper.getSingleCode("migrationTypes", pzPersonWithBLOBs.getMigrationType());
            if(sysCode4!=null){
                pzPersonWithBLOBs.setMigrationTypeName(sysCode4.getCodeName());
            }
            SysCode sysCode5 = sysCodeMapper.getSingleCode("bloodType", pzPersonWithBLOBs.getBloodType());
            if(sysCode5!=null){
                pzPersonWithBLOBs.setBloodTypeName(sysCode5.getCodeName());
            }
            SysCode sysCode6 = sysCodeMapper.getSingleCode("religion", pzPersonWithBLOBs.getpReligion());
            if(sysCode6!=null){
                pzPersonWithBLOBs.setpReligionName(sysCode6.getCodeName());
            }
            SysCode sysCode7 = sysCodeMapper.getSingleCode("healthCondition", pzPersonWithBLOBs.getHealthStatus());
            if(sysCode7!=null){
                pzPersonWithBLOBs.setHealthStatusName(sysCode7.getCodeName());
            }
            SysCode sysCode8 = sysCodeMapper.getSingleCode("healthCareType", pzPersonWithBLOBs.getMedicalInsuranceType());
            if(sysCode8!=null){
                pzPersonWithBLOBs.setMedicalInsuranceTypeName(sysCode8.getCodeName());
            }
            json.setObject(pzPersonWithBLOBs);
            json.setFlag(0);
            json.setMsg("ok");
        }catch (Exception e){
            e.printStackTrace();
            json.setMsg("err");
            json.setFlag(1);
        }
        return json;

    }
    public ToJson<PzPersonWithBLOBs> queryPerson(HttpServletRequest request, HttpServletResponse response, PzPersonWithBLOBs pzPersonWithBLOBs,
                                                 Integer page, Integer pageSize, boolean useFlag, String export){
        ToJson<PzPersonWithBLOBs> json = new ToJson<PzPersonWithBLOBs>(1,"error");
        PageParams pageParams=new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        pageParams.setUseFlag(useFlag);
        Map<String,Object> map=new HashMap<>();
        map.put("page", pageParams);
        Map<String, Object> param = new HashMap<String, Object>();
        Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
        param.put("userId", user.getUserId());
        param.put("userPriv", user.getUserPriv());
        param.put("deptId", user.getDeptId());
//       String pGridArray[]=pGridStr.split(",");
//       System.out.println(pGridArray.length);
//       if(pGridArray.length!=0) {
//           map.put("pGridStr", pGridArray);
//       }
        String menuModel=menuJdtMapper.selMenuByModel("1");
        if(!CheckAll.checkAll(menuModel,param)){
            pzPersonWithBLOBs.setCreateUser(user.getUserId());
        }
        map.put("pzPersonWithBLOBs",pzPersonWithBLOBs);

        try {
            if(export==null){
                export="0";
            }
            List<PzPersonWithBLOBs> pzPersonWithBLOBsList = pzPersonMapper.queryPerson(map);
            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
            for(PzPersonWithBLOBs pzPersonWithBLOBs1:pzPersonWithBLOBsList) {
                if ("0".equals(pzPersonWithBLOBs1.getpSex())) {
                    pzPersonWithBLOBs1.setpSexStr("男");
                } else {
                    pzPersonWithBLOBs1.setpSexStr("女");
                }
                if(pzPersonWithBLOBs1.getpDate() != null){
                    pzPersonWithBLOBs1.setpDateStr(sd.format(pzPersonWithBLOBs1.getpDate()));
                }
                SysCode sysCode = sysCodeMapper.getSingleCode("POLITICAL", pzPersonWithBLOBs1.getpPolitical());
                if (sysCode != null) {
                    pzPersonWithBLOBs1.setpPolitical(sysCode.getCodeName());
                }
                SysCode sysCode1 = sysCodeMapper.getSingleCode("DEGREE", pzPersonWithBLOBs1.getpEducation());
                if (sysCode1 != null) {
                    pzPersonWithBLOBs1.setpEducation(sysCode1.getCodeName());
                }
                if (!StringUtils.checkNull(pzPersonWithBLOBs1.getGridUserId())) {
                    pzPersonWithBLOBs1.setGridUserNames(usersService.getUserNameById(pzPersonWithBLOBs1.getGridUserId()));
                }
                if ("01".equals(pzPersonWithBLOBs1.getpMaritalStatus())) {
                    pzPersonWithBLOBs1.setpMaritalStatusStr("未婚");
                } else if(("02".equals(pzPersonWithBLOBs1.getpMaritalStatus())) ) {
                    pzPersonWithBLOBs1.setpMaritalStatusStr("已婚");
                }else{
                    pzPersonWithBLOBs1.setpMaritalStatusStr("离异");
                }
                if ("0".equals(pzPersonWithBLOBs1.getpVehicles())) {
                    pzPersonWithBLOBs1.setpVehiclesStr("无");
                } else {
                    pzPersonWithBLOBs1.setpVehiclesStr("有");
                }
                if ("0".equals(pzPersonWithBLOBs1.getpIsHouse())) {
                    pzPersonWithBLOBs1.setpIsHouseStr("无");
                } else {
                    pzPersonWithBLOBs1.setpIsHouseStr("有");
                }
                if ("1".equals(pzPersonWithBLOBs1.getFlag1())) {
                    pzPersonWithBLOBs1.setFlag1Str("户籍人口");
                } else {
                    pzPersonWithBLOBs1.setFlag1Str("流动人口");
                }

            }
            json.setObj(pzPersonWithBLOBsList);
            json.setFlag(0);
            json.setMsg("ok");
            json.setTotleNum(pzPersonMapper.queryCountPerson(pzPersonWithBLOBs));
            if(export.equals("1")){
                HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead("常住人口信息导出", 32);
                String[] secondTitles = {"所属网格", "姓名", "身份证", "曾用名/别名", "性别","出生日期","民族","联系方式","政治面貌","文化程度","婚姻状况","宗教信仰","职业","工作单位","户籍地址","籍贯","户籍地详址","名下机动车辆","有无固定住所","现居地址","车牌号","备注"};
                HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles);
                String[] beanProperty = {"gridName", "pName", "pCradId", "pAlias", "pSexStr", "pDateStr","pNation","pPhone","pPolitical","pEducation","pMaritalStatusStr","pReligion","pOccupation","pWorkUnit","pDomicile","pOrigin","pDetailedDomicile","pVehiclesStr","pIsHouseStr","pAddress","str1","pRemarks"};
                HSSFWorkbook workbook = null;
                workbook = ExcelUtil.exportExcelData(workbook2, pzPersonWithBLOBsList, beanProperty);
                OutputStream out = response.getOutputStream();
                String filename = "常住人口信息记录表.xls";
                filename = FileUtils.encodeDownloadFilename(filename, request.getHeader("user-agent"));
                response.setContentType("application/vnd.ms-excel;charset=UTF-8");
                response.setHeader("content-disposition", "attachment;filename=" + filename);
                workbook.write(out);
                out.close();
            }
        }catch (Exception e){
            e.printStackTrace();
            L.e("PzPersonService queryPerson:" + e);
        }
        return json;
    }

    public ToJson importPerson(MultipartFile file, HttpServletResponse response, HttpServletRequest request, HttpSession session) {
        ToJson<PzPersonWithBLOBs> toJson = new ToJson<PzPersonWithBLOBs>(1,"error");
        Users users= SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users());
        // 成功次数
        Integer successCount = 0;
        try {
            //判读当前系统
            //读取配置文件
            ResourceBundle rb = ResourceBundle.getBundle("upload");
            String osName = System.getProperty("os.name");
            StringBuffer path = new StringBuffer();
            if (osName.toLowerCase().startsWith("win")) {
                path = path.append(rb.getString("upload.win"));
            } else {
                path = path.append(rb.getString("upload.linux"));
            }
            // 判断是否为空文件
            if (file.isEmpty()) {
                toJson.setMsg("请上传文件！");
                toJson.setFlag(1);
                return toJson;
            } else {
                String fileName = file.getOriginalFilename();
                if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    int pos = fileName.indexOf(".");
                    String extName = fileName.substring(pos);
                    String newFileName = uuid + extName;
                    File dest = new File(path.toString(), newFileName);
                    file.transferTo(dest);
                    // 将文件上传成功后进行读取文件
                    // 进行读取的路径
                   // String readPath = path.append(newFileName).toString();
                    String readPath = path.append(System.getProperty("file.separator")).append(newFileName).toString();
                    InputStream in = new FileInputStream(readPath);
                    HSSFWorkbook excelObj = new HSSFWorkbook(in);
                    HSSFSheet sheetObj = excelObj.getSheetAt(0);
                    Row row = sheetObj.getRow(0);
                    int colNum = row.getPhysicalNumberOfCells();
                    int lastRowNum = sheetObj.getLastRowNum();
                    List<PzPersonWithBLOBs> saveList = new ArrayList<PzPersonWithBLOBs>();
                    PzPersonWithBLOBs pzPersonWithBLOBs = null;
                    SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
                    for (int i = 1; i < lastRowNum; i++) {
                        pzPersonWithBLOBs = new PzPersonWithBLOBs();
                        row = sheetObj.getRow(i);
                        String value = "";
                        if (row != null) {
                            for (int j = 0; j < colNum; j++) {
                                Cell cell = row.getCell(j);
                                if (cell != null) {
                                    switch (j) {
                                        case 0:
                                            //所属网格
                                            String as=cell.getStringCellValue().trim();
                                            GridInfo info=gridInfoMapper.selectByUGridName(as);
                                            pzPersonWithBLOBs.setpGrid(info.getGridId());
                                            break;
                                        case 1:
                                            // 姓名
                                            pzPersonWithBLOBs.setpName(cell.getStringCellValue());
                                            break;
                                        case 2:
                                            // 身份证
                                            pzPersonWithBLOBs.setpCradId(cell.getStringCellValue());
                                            break;
                                        case 3:
                                            // 别名
                                            pzPersonWithBLOBs.setpAlias(cell.getStringCellValue());
                                            break;
                                        case 4:
                                            // 性别
                                            if("男".equals(cell.getStringCellValue().trim())){
                                                pzPersonWithBLOBs.setpSex("0");
                                            }else if("女".equals(cell.getStringCellValue().trim())){
                                                pzPersonWithBLOBs.setpSex("1");
                                            }
                                            break;
                                        case 5:
                                            // 出生日期

                                            pzPersonWithBLOBs.setpDate(sd.parse(cell.getStringCellValue().trim()));
                                            break;
                                        case 6:
                                            // 民族
                                            pzPersonWithBLOBs.setpNation(cell.getStringCellValue());
                                            break;
                                        case 7:
                                            // 联系方式
                                            pzPersonWithBLOBs.setpPhone(cell.getStringCellValue());
                                            break;
                                        case 8:
                                            // 政治面貌
                                            pzPersonWithBLOBs.setpPolitical((sysCodeMapper.getByName("POLITICAL",cell.getStringCellValue().trim())).getCodeNo());
                                            break;
                                        case 9:
                                            // 文化程度
                                            pzPersonWithBLOBs.setpEducation((sysCodeMapper.getByName("DEGREE",cell.getStringCellValue().trim())).getCodeNo());
                                            break;
                                        case 10:
                                            // 婚姻状况
                                            if("未婚".equals(cell.getStringCellValue().trim())){
                                                pzPersonWithBLOBs.setpMaritalStatus("01");
                                            }else if("已婚".equals(cell.getStringCellValue().trim())){
                                                pzPersonWithBLOBs.setpMaritalStatus("02");
                                            }
                                            break;
                                        case 11:
                                            //宗教信仰
                                            pzPersonWithBLOBs.setpReligion(cell.getStringCellValue());
                                            break;
                                        case 12:
                                            //职业
                                            pzPersonWithBLOBs.setpOccupation(cell.getStringCellValue());
                                            break;
                                        case 13:
                                            //工作单位
                                            pzPersonWithBLOBs.setpWorkUnit(cell.getStringCellValue());
                                            break;
                                        case 14:
                                            //户籍地址
                                            pzPersonWithBLOBs.setpDomicile(cell.getStringCellValue());
                                            break;
                                        case 15:
                                            //籍贯
                                            pzPersonWithBLOBs.setpOrigin(cell.getStringCellValue());
                                            break;
                                        case 16:
                                            //户籍地详址
                                            pzPersonWithBLOBs.setpDetailedDomicile(cell.getStringCellValue());
                                            break;
                                        case 17:
                                            //名下机动车辆
                                            if("无".equals(cell.getStringCellValue().trim())){
                                                pzPersonWithBLOBs.setpVehicles("0");
                                            }else if("有".equals(cell.getStringCellValue().trim())){
                                                pzPersonWithBLOBs.setpVehicles("1");
                                            }
                                            break;
                                        case 18:
                                            //备注
                                            pzPersonWithBLOBs.setpRemarks(cell.getStringCellValue());
                                            break;
                                        case 19:
                                            //有无固定住所
                                            if("无".equals(cell.getStringCellValue().trim())){
                                                pzPersonWithBLOBs.setpIsHouse("0");
                                            }else if("有".equals(cell.getStringCellValue().trim())){
                                                pzPersonWithBLOBs.setpIsHouse("1");
                                            }
                                            break;
                                        case 20:
                                            //现居地址
                                            pzPersonWithBLOBs.setpAddress(cell.getStringCellValue());
                                            break;
                                        case 21:
                                            //特殊人员标记
                                            String specialStr = cell.getStringCellValue().trim();
                                            String str = "";
                                            if(specialStr.contains("刑满释放人员")){
                                                str += "1,";
                                            }
                                            if(specialStr.contains("社区矫正人员")){
                                                str += "2,";
                                            }
                                            if(specialStr.contains("重点信访人员")){
                                                str += "3,";
                                            }
                                            if(specialStr.contains("易肇事肇祸严重精神障碍患者")){
                                                str += "4,";
                                            }
                                            if(specialStr.contains("吸毒人员")){
                                                str += "5,";
                                            }
                                            if(specialStr.contains("重点青少年")){
                                                str += "6,";
                                            }
                                            pzPersonWithBLOBs.setSpecialStr(str);
                                            break;
                                        case 22:
                                            //实口类型
                                            if("流动人口".equals(cell.getStringCellValue().trim())){
                                                pzPersonWithBLOBs.setFlag1("2");
                                            }else if("户籍人口".equals(cell.getStringCellValue().trim())){
                                                pzPersonWithBLOBs.setFlag1("1");
                                            }
                                            break;
                                        case 23:
                                            //车牌号
                                            cell.setCellType(CellType.STRING);
                                            pzPersonWithBLOBs.setStr1(cell.getStringCellValue());
                                            break;
                                        default:
                                            toJson.setFlag(0);
                                            toJson.setMsg("err");
                                            break;
                                    }
                                }

                            }
                            pzPersonWithBLOBs.setCreateUser(users.getUserId());
                            pzPersonWithBLOBs.setCreateTime(DateFormat.getCurrentTime());
                            pzPersonWithBLOBs.setFlag2("0");
                            pzPersonWithBLOBs.setFlag1("1");
                            //将数据放入数据库
                            int count=pzPersonMapper.insertSelective(pzPersonWithBLOBs);
                            if(count>0) {
                                successCount = successCount + count;
                            }
                            dest.delete();
                        }
                    }

                }
            }
            if(successCount>0){
                toJson.setTotleNum(successCount);
                toJson.setMsg("ok");
                toJson.setFlag(0);
                return  toJson;
            }
        } catch (Exception e) {
            //读取配置文件,获取文件要存储的路径
            StringBuffer path = this.getPath();
            String fileName = file.getOriginalFilename();
            if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                String extName = fileName
                        .substring(fileName.lastIndexOf(".") + 1);// 文件后缀
                String newFileName = uuid + extName;//组合成新的文件名
                File dest = new File(path.toString(), newFileName);
                dest.delete();
            }
            e.getMessage();
            e.printStackTrace();
        }

        return toJson;
    }

    //判读当前系统,读取配置文件,返回路径
    public StringBuffer getPath(){
        ResourceBundle rb = ResourceBundle.getBundle("upload");
        String osName = System.getProperty("os.name");
        StringBuffer path = new StringBuffer();
        if (osName.toLowerCase().startsWith("win")) {
            path = path.append(rb.getString("upload.win"));
        } else {
            path = path.append(rb.getString("upload.linux"));
        }
        return path;
    }

    public ToJson<PzPersonWithBLOBs> queryPersonAlaways(HttpServletRequest request, HttpServletResponse response, PzPersonWithBLOBs pzPersonWithBLOBs, Integer page, Integer pageSize, boolean useFlag, String export) {
        ToJson<PzPersonWithBLOBs> json = new ToJson<PzPersonWithBLOBs>(1,"error");
        PageParams pageParams=new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        pageParams.setUseFlag(useFlag);
        Map<String,Object> map=new HashMap<>();
        map.put("page", pageParams);
        Map<String, Object> param = new HashMap<String, Object>();
        Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
        param.put("userId", user.getUserId());
        param.put("userPriv", user.getUserPriv());
        param.put("deptId", user.getDeptId());
        String menuModel=menuJdtMapper.selMenuByModel("1");
        if(!CheckAll.checkAll(menuModel,param)){
            pzPersonWithBLOBs.setCreateUser(user.getUserId());
        }
        map.put("pzPersonWithBLOBs",pzPersonWithBLOBs);
        try {
            if(export==null){
                export="0";
            }
            List<PzPersonWithBLOBs> pzPersonWithBLOBsList = pzPersonMapper.queryPerson(map);
            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
            List<PzPersonWithBLOBs> list = new ArrayList<>();
            for(PzPersonWithBLOBs pzPersonWithBLOBs1:pzPersonWithBLOBsList) {
                if(pzPersonWithBLOBs1.getFlag1() == "1"){
                    list.add(pzPersonWithBLOBs1);
                }else {
                    if ("0".equals(pzPersonWithBLOBs1.getpSex())) {
                        pzPersonWithBLOBs1.setpSexStr("男");
                    } else {
                        pzPersonWithBLOBs1.setpSexStr("女");
                    }
                    if(pzPersonWithBLOBs1.getpDate() != null){
                        pzPersonWithBLOBs1.setpDateStr(sd.format(pzPersonWithBLOBs1.getpDate()));
                    }
                    SysCode sysCode = sysCodeMapper.getSingleCode("POLITICAL", pzPersonWithBLOBs1.getpPolitical());
                    if (sysCode != null) {
                        pzPersonWithBLOBs1.setpPolitical(sysCode.getCodeName());
                    }
                    SysCode sysCode1 = sysCodeMapper.getSingleCode("DEGREE", pzPersonWithBLOBs1.getpEducation());
                    if (sysCode1 != null) {
                        pzPersonWithBLOBs1.setpEducation(sysCode1.getCodeName());
                    }
                    if (!StringUtils.checkNull(pzPersonWithBLOBs1.getGridUserId())) {
                        pzPersonWithBLOBs1.setGridUserNames(usersService.getUserNameById(pzPersonWithBLOBs1.getGridUserId()));
                    }
                    if ("01".equals(pzPersonWithBLOBs1.getpMaritalStatus())) {
                        pzPersonWithBLOBs1.setpMaritalStatusStr("未婚");
                    } else {
                        pzPersonWithBLOBs1.setpMaritalStatusStr("已婚");
                    }
                    if ("0".equals(pzPersonWithBLOBs1.getpVehicles())) {
                        pzPersonWithBLOBs1.setpVehiclesStr("无");
                    } else {
                        pzPersonWithBLOBs1.setpVehiclesStr("有");
                    }
                    if ("0".equals(pzPersonWithBLOBs1.getpIsHouse())) {
                        pzPersonWithBLOBs1.setpIsHouseStr("无");
                    } else {
                        pzPersonWithBLOBs1.setpIsHouseStr("有");
                    }
                    list.add(pzPersonWithBLOBs1);
                }

            }
            pzPersonWithBLOBsList.removeAll(list);
            json.setObj(pzPersonWithBLOBsList);
            json.setFlag(0);
            json.setMsg("ok");
            json.setTotleNum(pzPersonMapper.queryCountPerson(pzPersonWithBLOBs));
            if(export.equals("1")){
                HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead("常住人口信息导出", 32);
                String[] secondTitles = {"所属网格", "姓名", "身份证", "曾用名/别名", "性别","出生日期","民族","联系方式","政治面貌","文化程度","婚姻状况","宗教信仰","职业","工作单位","户籍地址","籍贯","户籍地详址","名下机动车辆","备注","有无固定住所","现居地址","车牌号"};
                HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles);
                String[] beanProperty = {"gridName", "pName", "pCradId", "pAlias", "pSexStr", "pDateStr","pNation","pPhone","pPolitical","pEducation","pMaritalStatusStr","pReligion","pOccupation","pWorkUnit","pDomicile","pOrigin","pDetailedDomicile","pVehiclesStr","pRemarks","pIsHouseStr","pAddress","str1"};
                HSSFWorkbook workbook = null;
                workbook = ExcelUtil.exportExcelData(workbook2, pzPersonWithBLOBsList, beanProperty);
                OutputStream out = response.getOutputStream();
                String filename = "常住人口信息记录表.xls";
                filename = FileUtils.encodeDownloadFilename(filename, request.getHeader("user-agent"));
                response.setContentType("application/vnd.ms-excel;charset=UTF-8");
                response.setHeader("content-disposition", "attachment;filename=" + filename);
                workbook.write(out);
                out.close();
            }
        }catch (Exception e){
            e.printStackTrace();
            L.e("PzPersonService queryPersonAlaways:" + e);
        }
        return json;
    }

    public ToJson importPersonAlaways(MultipartFile file, HttpServletResponse response, HttpServletRequest request, HttpSession session) {
        ToJson<PzPersonWithBLOBs> toJson = new ToJson<PzPersonWithBLOBs>(1,"error");
        Users users= SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users());
        // 成功次数
        Integer successCount = 0;
        try {
            //判读当前系统
            //读取配置文件
            ResourceBundle rb = ResourceBundle.getBundle("upload");
            String osName = System.getProperty("os.name");
            StringBuffer path = new StringBuffer();
            if (osName.toLowerCase().startsWith("win")) {
                path = path.append(rb.getString("upload.win"));
            } else {
                path = path.append(rb.getString("upload.linux"));
            }
            // 判断是否为空文件
            if (file.isEmpty()) {
                toJson.setMsg("请上传文件！");
                toJson.setFlag(1);
                return toJson;
            } else {
                String fileName = file.getOriginalFilename();
                if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    int pos = fileName.indexOf(".");
                    String extName = fileName.substring(pos);
                    String newFileName = uuid + extName;
                    File dest = new File(path.toString(), newFileName);
                    file.transferTo(dest);
                    // 将文件上传成功后进行读取文件
                    // 进行读取的路径
                    String readPath = path.append(newFileName).toString();
                    InputStream in = new FileInputStream(readPath);
                    HSSFWorkbook excelObj = new HSSFWorkbook(in);
                    HSSFSheet sheetObj = excelObj.getSheetAt(0);
                    Row row = sheetObj.getRow(0);
                    int colNum = row.getPhysicalNumberOfCells();
                    int lastRowNum = sheetObj.getLastRowNum();
                    List<PzPersonWithBLOBs> saveList = new ArrayList<PzPersonWithBLOBs>();
                    PzPersonWithBLOBs pzPersonWithBLOBs = null;
                    SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
                    for (int i = 1; i <= lastRowNum; i++) {
                        pzPersonWithBLOBs = new PzPersonWithBLOBs();
                        row = sheetObj.getRow(i);
                        String value = "";
                        if (row != null) {
                            for (int j = 0; j < colNum; j++) {
                                Cell cell = row.getCell(j);
                                if (cell != null) {
                                    switch (j) {
                                        case 0:
                                            //所属网格
                                            String as=cell.getStringCellValue().trim();
                                            GridInfo info=gridInfoMapper.selectByUGridName(as);
                                            pzPersonWithBLOBs.setpGrid(info.getGridId());
                                            break;
                                        case 1:
                                            // 姓名
                                            pzPersonWithBLOBs.setpName(cell.getStringCellValue());
                                            break;
                                        case 2:
                                            // 身份证
                                            pzPersonWithBLOBs.setpCradId(cell.getStringCellValue());
                                            break;
                                        case 3:
                                            // 别名
                                            pzPersonWithBLOBs.setpAlias(cell.getStringCellValue());
                                            break;
                                        case 4:
                                            // 性别
                                            if("男".equals(cell.getStringCellValue().trim())){
                                                pzPersonWithBLOBs.setpSex("0");
                                            }else if("女".equals(cell.getStringCellValue().trim())){
                                                pzPersonWithBLOBs.setpSex("1");
                                            }
                                            break;
                                        case 5:
                                            // 出生日期

                                            pzPersonWithBLOBs.setpDate(sd.parse(cell.getStringCellValue().trim()));
                                            break;
                                        case 6:
                                            // 民族
                                            pzPersonWithBLOBs.setpNation(cell.getStringCellValue());
                                            break;
                                        case 7:
                                            // 联系方式
                                            pzPersonWithBLOBs.setpPhone(cell.getStringCellValue());
                                            break;
                                        case 8:
                                            // 政治面貌
                                            pzPersonWithBLOBs.setpPolitical((sysCodeMapper.getByName("POLITICAL",cell.getStringCellValue().trim())).getCodeNo());
                                            break;
                                        case 9:
                                            // 文化程度
                                            pzPersonWithBLOBs.setpEducation((sysCodeMapper.getByName("DEGREE",cell.getStringCellValue().trim())).getCodeNo());
                                            break;
                                        case 10:
                                            // 婚姻状况
                                            if("未婚".equals(cell.getStringCellValue().trim())){
                                                pzPersonWithBLOBs.setpMaritalStatus("01");
                                            }else if("已婚".equals(cell.getStringCellValue().trim())){
                                                pzPersonWithBLOBs.setpMaritalStatus("02");
                                            }
                                            break;
                                        case 11:
                                            //宗教信仰
                                            pzPersonWithBLOBs.setpReligion(cell.getStringCellValue());
                                            break;
                                        case 12:
                                            //职业
                                            pzPersonWithBLOBs.setpOccupation(cell.getStringCellValue());
                                            break;
                                        case 13:
                                            //工作单位
                                            pzPersonWithBLOBs.setpWorkUnit(cell.getStringCellValue());
                                            break;
                                        case 14:
                                            //户籍地址
                                            pzPersonWithBLOBs.setpDomicile(cell.getStringCellValue());
                                            break;
                                        case 15:
                                            //籍贯
                                            pzPersonWithBLOBs.setpOrigin(cell.getStringCellValue());
                                            break;
                                        case 16:
                                            //户籍地详址
                                            pzPersonWithBLOBs.setpDetailedDomicile(cell.getStringCellValue());
                                            break;
                                        case 17:
                                            //名下机动车辆
                                            if("无".equals(cell.getStringCellValue().trim())){
                                                pzPersonWithBLOBs.setpVehicles("0");
                                            }else if("有".equals(cell.getStringCellValue().trim())){
                                                pzPersonWithBLOBs.setpVehicles("1");
                                            }
                                            break;
                                        case 18:
                                            //备注
                                            pzPersonWithBLOBs.setpRemarks(cell.getStringCellValue());
                                            break;
                                        case 19:
                                            //有无固定住所
                                            if("无".equals(cell.getStringCellValue().trim())){
                                                pzPersonWithBLOBs.setpIsHouse("0");
                                            }else if("有".equals(cell.getStringCellValue().trim())){
                                                pzPersonWithBLOBs.setpIsHouse("1");
                                            }
                                            break;
                                        case 20:
                                            //现居地址
                                            pzPersonWithBLOBs.setpAddress(cell.getStringCellValue());
                                            break;
                                        case 21:
                                            //特殊人员标记
                                            if("刑满释放人员".equals(cell.getStringCellValue().trim())){
                                                pzPersonWithBLOBs.setSpecialStr("1");
                                            } else if("社区矫正人员".equals(cell.getStringCellValue().trim())){
                                                pzPersonWithBLOBs.setSpecialStr("2");
                                            }else if("重点信访人员".equals(cell.getStringCellValue().trim())){
                                                pzPersonWithBLOBs.setSpecialStr("3");
                                            }else if("易肇事肇祸严重精神障碍患者".equals(cell.getStringCellValue().trim())){
                                                pzPersonWithBLOBs.setSpecialStr("4");
                                            }else if("吸毒人员".equals(cell.getStringCellValue().trim())){
                                                pzPersonWithBLOBs.setSpecialStr("5");
                                            }else if("重点青少年".equals(cell.getStringCellValue().trim())){
                                                pzPersonWithBLOBs.setSpecialStr("6");
                                            }
                                            break;
                                        case 23:
                                            //车牌号
                                            cell.setCellType(CellType.STRING);
                                            pzPersonWithBLOBs.setStr1(cell.getStringCellValue());
                                            break;
                                        default:
                                            toJson.setFlag(0);
                                            toJson.setMsg("err");
                                            break;
                                    }
                                }

                            }
                            pzPersonWithBLOBs.setCreateUser(users.getUserId());
                            pzPersonWithBLOBs.setCreateTime(DateFormat.getCurrentTime());
                            //将数据放入数据库
                            int count=pzPersonMapper.insertSelective(pzPersonWithBLOBs);
                            if(count>0) {
                                successCount = successCount + count;
                            }
                            dest.delete();
                        }
                    }

                }
            }
            if(successCount>0){
                toJson.setTotleNum(successCount);
                toJson.setMsg("ok");
                toJson.setFlag(0);
                return  toJson;
            }
        } catch (Exception e) {
            //读取配置文件,获取文件要存储的路径
            StringBuffer path = this.getPath();
            String fileName = file.getOriginalFilename();
            if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                String extName = fileName
                        .substring(fileName.lastIndexOf(".") + 1);// 文件后缀
                String newFileName = uuid + extName;//组合成新的文件名
                File dest = new File(path.toString(), newFileName);
                dest.delete();
            }
            e.getMessage();
            e.printStackTrace();
        }

        return toJson;
    }

    public ToJson addPersons(PzPersonWithBLOBs pzPersonWithBLOBs, HttpServletRequest request){
        ToJson toJson=new ToJson();

        try {
            Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
            pzPersonWithBLOBs.setCreateUser(user.getUserId());
            pzPersonWithBLOBs.setCreateTime(DateFormat.getDatestr(new Date()));
            pzPersonWithBLOBs.setFlag2("0");
            //标识不是户主
            pzPersonWithBLOBs.setIsHousehold(2);
            pzPersonMapper.insertSelective(pzPersonWithBLOBs);
            //判断 流动人口
            if(pzPersonWithBLOBs.getFlag1().equals("2")){
                PzPersonFlow flow=new PzPersonFlow();
                if(pzPersonWithBLOBs.getpId()!=null){
                    flow.setPersonId(String.valueOf(pzPersonWithBLOBs.getpId()));
                }
                pzPersonFlowMapper.insertSelective(flow);
            }
            toJson.setObject(pzPersonWithBLOBs);
            toJson.setFlag(0);
            toJson.setMsg("ok");
        }catch (Exception e){
            e.printStackTrace();
            toJson.setMsg("err");
            toJson.setFlag(1);
        }
        return toJson;
    }



    public ToJson selectAll(){
        ToJson<PzPerson> toJson=new ToJson<PzPerson>();
        List<SysCode> list=sysCodeMapper.getAllCode();
        List<PzPerson> relationships=new ArrayList<>();
        List<PzPerson> accountCategorys=new ArrayList<>();
        List<PzPerson> MigrationTypes=new ArrayList<>();
        List<PzPerson> BloodTypes=new ArrayList<>();
        List<PzPerson> pReligions=new ArrayList<>();
        List<PzPerson> healthStatuss=new ArrayList<>();
        List<PzPerson> medicalInsuranceTypes=new ArrayList<>();
        List<PzPerson> pEducations=new ArrayList<>();
        List<PzPerson> pPoliticals=new ArrayList<>();
        List<PzPerson> xl=new ArrayList<>();
        PzPerson pzPersons=new PzPerson();
        if(list.size()>0){
            for(SysCode sysCode:list){
                //与户主关系
                if(sysCode.getParentNo().trim().equals("relationship")){
                    PzPerson pzPerson=new PzPerson();
                    pzPerson.setRelationshipId(sysCode.getCodeNo());
                    pzPerson.setRelationshipName(sysCode.getCodeName());
                    relationships.add(pzPerson);
                }
                //户口类别
                if(sysCode.getParentNo().trim().equals("registeredResidenceType")){
                    PzPerson pzPerson=new PzPerson();
                    pzPerson.setAccountCategoryId(sysCode.getCodeNo());
                    pzPerson.setAccountCategoryName(sysCode.getCodeName());
                    accountCategorys.add(pzPerson);
                }
                //迁移类型
                if(sysCode.getParentNo().trim().equals("migrationTypes")){
                    PzPerson pzPerson=new PzPerson();
                    pzPerson.setMigrationTypeId(sysCode.getCodeNo());
                    pzPerson.setMigrationTypeName(sysCode.getCodeName());
                    MigrationTypes.add(pzPerson);
                }
                //血型
                if(sysCode.getParentNo().trim().equals("bloodType")){
                    PzPerson pzPerson=new PzPerson();
                    pzPerson.setBloodTypeId(sysCode.getCodeNo());
                    pzPerson.setBloodTypeName(sysCode.getCodeName());
                    BloodTypes.add(pzPerson);
                }
                //宗教信仰
                if(sysCode.getParentNo().trim().equals("religion")){
                    PzPerson pzPerson=new PzPerson();
                    pzPerson.setpReligionId(sysCode.getCodeNo());
                    pzPerson.setpReligionName(sysCode.getCodeName());
                    pReligions.add(pzPerson);
                }
                //健康状况
                if(sysCode.getParentNo().trim().equals("healthCondition")){
                    PzPerson pzPerson=new PzPerson();
                    pzPerson.setHealthStatusId(sysCode.getCodeNo());
                    pzPerson.setHealthStatusName(sysCode.getCodeName());
                    healthStatuss.add(pzPerson);
                }

                //医保类型
                if(sysCode.getParentNo().trim().equals("healthCareType")){
                    PzPerson pzPerson=new PzPerson();
                    pzPerson.setMedicalInsuranceTypeId(sysCode.getCodeNo());
                    pzPerson.setMedicalInsuranceTypeName(sysCode.getCodeName());
                    medicalInsuranceTypes.add(pzPerson);
                }
                //文化程度
                if(sysCode.getParentNo().trim().equals("educationBackground")){
                    PzPerson pzPerson=new PzPerson();
                    pzPerson.setpEducationId(sysCode.getCodeNo());
                    pzPerson.setpEducationName(sysCode.getCodeName());
                    pEducations.add(pzPerson);
                }
                //政治面貌
                if(sysCode.getParentNo().trim().equals("POLITICAL")){
                    PzPerson pzPerson=new PzPerson();
                    pzPerson.setpPoliticalId(sysCode.getCodeNo());
                    pzPerson.setpPoliticalName(sysCode.getCodeName());
                    pPoliticals.add(pzPerson);
                }
                //学历
                if(sysCode.getParentNo().trim().equals("DEGREE")){
                    PzPerson pzPerson=new PzPerson();
                    pzPerson.setXlId(sysCode.getCodeNo());
                    pzPerson.setXlName(sysCode.getCodeName());
                    xl.add(pzPerson);
                }

            }
            pzPersons.setRelationships(relationships);
            pzPersons.setAccountCategorys(accountCategorys);
            pzPersons.setMigrationTypes(MigrationTypes);
            pzPersons.setBloodTypes(BloodTypes);
            pzPersons.setpReligions(pReligions);
            pzPersons.setHealthStatuss(healthStatuss);
            pzPersons.setMedicalInsuranceTypes(medicalInsuranceTypes);
            pzPersons.setpEducations(pEducations);
            pzPersons.setpPoliticals(pPoliticals);
            pzPersons.setXl(xl);
            toJson.setObject(pzPersons);
            toJson.setFlag(0);
            toJson.setMsg("ok");
        }
        return toJson;
    }
}
